﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Common.Encrypt
{
    public class Md5Crypt
    {
        /// <summary>
        /// 生成MD5 hash码，返回32个字符的16进制格式字符串，默认UTF8编码，默认字符是小写
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <param name="encoding">编码</param>
        /// <param name="isUpperCase">是否大写</param>
        /// <returns></returns>
        public static string MD5(string input, Encoding encoding = null, bool isUpperCase = false)
        {
            if (encoding == null)
                encoding = Encoding.UTF8;

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(encoding.GetBytes(input));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));

            string rStr = sb.ToString();
            if (isUpperCase)
                rStr = rStr.ToUpper();

            return rStr;
        }
    }
}